<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends CI_Controller 
{
	/* 后台首页 */
	public function index() 
	{
		echo 'admin index';
	}
	
	/* 登录 */
	public function login() 
	{
		$output = array('code' => 1, 'msg' => '登录失败');
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		try {
			if (empty($username) || empty($password)) 
			{
				throw new Exception('帐号和密码不能为空', 2);	
			}
			
			if (!($username === ADMIN_LOGIN && $password === ADMIN_PASSWORD)) {
				throw  new Exception('帐号或密码错误', 3);
			}
			$output = array('code' => 0, 'msg' => '登录成功');
			$this->session->set_userdata(array('username' => $username, 'password' => $password, 'isLogin' => true));
		} catch (Exception $e) {
			$output['code'] = $e->getCode();
			$output['msg'] = $e->getMessage();
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	/* 登出 */
	public function logout() 
	{
		$output = array('code' => 1, 'msg' => '登出成功');
		$this->session->set_userdata(array('username' => '', 'password' => '', 'isLogin' => false));
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	/* 用户登录 */
	public function userLogin() {
		$output = array('code' => 1, 'msg' => '登录失败');
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		try {
			if (empty($username) || empty($password)) 
			{
				throw new Exception('帐号和密码不能为空', 2);	
			}
			
			if (!($username === ADMIN_LOGIN && $password === ADMIN_PASSWORD)) {
				throw  new Exception('帐号或密码错误', 3);
			}
			$output = array('code' => 0, 'msg' => '登录成功');
			$this->session->set_userdata(array('username' => $username, 'password' => $password, 'userLogin' => true));
		} catch (Exception $e) {
			$output['code'] = $e->getCode();
			$output['msg'] = $e->getMessage();
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	/* 用户登出 */
	public function userLogout() {
		$output = array('code' => 1, 'msg' => '登出成功');
		$this->session->set_userdata(array('username' => '', 'password' => '', 'userLogin' => false));
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	/* 处理菜单编辑 */
	public function processMenuFrom() {
		$output = array('code' => 1, 'msg' => '', 'action' => '错误!' );
		try {
			$id = $this->input->post('id');
			$parentId = $this->input->post('parent_id');
			$name = $this->input->post('name');
			$icon = $this->input->post('icon');
			$url = $this->input->post('url');
			$isShow = $this->input->post('is_show');
			$action = $this->input->post('action');
			if ($action == 'edit' ) {
				//编辑
				if (empty($id) || !is_numeric($id)) {
					throw new Exception('错误!', 2);
				}
				if ($this->_isFirstLevel($id)) {
					throw new Exception('不能编辑一级菜单!', 2);
				}
				if ($parentId == 0) {
					throw new Exception('不能修改为一级菜单', 2);
				}
				$sql = "UPDATE menu SET icon = '$icon', parent_id = '$parentId', name = '$name', url = '$url', is_show = '$isShow' WHERE id = '$id'";
				$this->db->query($sql);
				$afftedNum = $this->db->affected_rows();
				if ($afftedNum == 0) {
					//throw new Exception('错误!', 2);
				}
			}
			if ($action == 'add') {
				if ($parentId == 0) {
					throw new Exception('不能添加一级菜单!', 2);
				}
				$sql = "INSERT INTO menu (parent_id, is_show, name, icon, url) VALUES ('$parentId', '$isShow', '$name', '$icon', '$url')";
				$this->db->query($sql);
				$afftedNum = $this->db->affected_rows();
				if ($afftedNum == 0) {
					//throw new Exception('错误!', 2);
				}
				$id = $this->db->insert_id();
			}
			$output['code'] = 0;
			$output['msg'] = array('id' => $id, 'parent_id' => $parentId, 'name' => $name, 'url' => $url, 'is_show' => $isShow);
			$output['action'] = $action;
		}
		catch (Exception $e) {
			$output['code'] = $e->getCode();
			$output['msg'] = $e->getMessage();
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	/* 删除菜单 */
	public function delMenu() {
		$id = $this->input->get('delId');
		$output = array('code' => 1, 'msg' => '' );
		try {
			if (empty($id) || !is_numeric($id)) {
				throw new Exception('错误,没有你要删除的项目', 2);
			}
			if (!$this->_isMenuCanDelete($id)) {
				throw new Exception('请先删除全部子菜单', 2);
			}
			if ($this->_isFirstLevel($id)) {
				throw new Exception('不能删除一级菜单');
			}
			$sql = "DELETE FROM menu WHERE id = '$id' LIMIT 1";
			$this->db->query($sql);
			$afftedNum = $this->db->affected_rows();
			if ($afftedNum == 0) {
					//throw new Exception('错误!', 2);
			}
			$output['code'] = 0;
			$output['msg'] = '成功删除!';
			$output['delId'] = $id;
		}
		catch (Exception $e) {
			$output['code'] = $e->getCode();
			$output['msg'] = $e->getMessage();
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	/* 判断菜单是否为一级菜单 */
	private function _isFirstLevel($id) {
		$query = $this->db->query("SELECT * FROM menu WHERE id = '$id' LIMIT 1");
		$row = $query->row_array();
		if ($row['parent_id'] == 0) {
			return true;
		}
		else {
			return false;
		}
	}
	
	/* 判断菜单是否可以删除 */
	private function _isMenuCanDelete($id) {
		$query = $this->db->query("SELECT * FROM menu WHERE parent_id = '$id' LIMIT 1");
		$row = $query->row_array();
		if (empty($row)) {
			return true;
		}
		else {
			return false;
		}
	}
	
	/* 获取制定菜单信息 */
	public function queryMenu() {
		$id = $this->input->get('id');
		$output = array('code' => 1, 'msg' => array() );
		try {
			if (empty($id) || !is_numeric($id)) {
				throw new Exception('', 2);
			}
			
			$query = $this->db->query("SELECT *, (SELECT name FROM menu B WHERE B.id = A.parent_id LIMIT 1 ) parent_name FROM menu A WHERE id = '$id' LIMIT 1");
			$row = $query->row_array();
			$output['code'] = 0;
			$output['msg'] = $row;
		}
		catch(Exception $e) {
			$output['code'] = $e->getCode();
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	/* 获取菜单列表 */
	public function getMenuList() {
		$output = array();
		$id = $this->input->get('id');
		if (empty($id) || !is_numeric($id)) {
			$id = 0;
		}
		$query = $this->db->query("SELECT * FROM menu WHERE id != '$id'");
		foreach ($query->result_array() as $row)
		{
    		$output[] =  $row;
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
	
	
	/* 上传图片 */
	public function uploadIcon() {
		//var_dump($_FILES);
		//exit();
		$output = array('fileName' => '');
		$POST_MAX_SIZE = ini_get('post_max_size');
        $unit = strtoupper(substr($POST_MAX_SIZE, - 1));
        $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
        if ((int) $_SERVER['CONTENT_LENGTH'] > $multiplier * (int) $POST_MAX_SIZE && $POST_MAX_SIZE)
        {
        	header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
            echo "POST exceeded maximum allowed size.";
            exit(0);
        }
        // Settings
        $save_path = APPPATH . '../' . 'icon/';
		$upload_name = 'Filedata';
		$max_file_size_in_bytes = 2147483647; // 2GB in bytes
		$extension_whitelist = array("jpg", "gif", "png", "bmp");
		$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';
		$MAX_FILENAME_LENGTH = 260;
		$file_name = "";
		$file_extension = "";
		$uploadErrors = array(0 => "There is no error, the file uploaded successfully", 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini", 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 3 => "The uploaded file was only partially uploaded", 4 => "No file was uploaded", 
            6 => "Missing a temporary folder");
		if (! isset($_FILES[$upload_name]))
        {
        	echo "No upload found in \$_FILES for " . $upload_name;
        	exit(0);
        }
		else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0)
        {
            echo $uploadErrors[$_FILES[$upload_name]["error"]];
            exit(0);
        }
        else if (! isset($_FILES[$upload_name]["tmp_name"]) || ! @is_uploaded_file($_FILES[$upload_name]["tmp_name"]))
        {
            echo "Upload failed is_uploaded_file test.";
            exit(0);
        }
        else if (! isset($_FILES[$upload_name]['name']))
        {
            echo "File has no name.";
            exit(0);
        }
        $file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
		if (! $file_size || $file_size > $max_file_size_in_bytes)
        {
            echo "File exceeds the maximum allowed size";
            exit(0);
        }
        if ($file_size <= 0)
        {
            echo "File size outside allowed lower bound";
            exit(0);
        }
        $path_info = pathinfo($_FILES[$upload_name]['name']);
        $file_extension = strtolower($path_info["extension"]);
        $file_name = md5(microtime()) . ".$file_extension";
		if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH)
        {
            echo "Invalid file name";
            exit(0);
        }
		if (file_exists($save_path . $file_name))
        {
            echo "File with this name already exists";
            exit(0);
        }
        $is_valid_extension = false;
		foreach ($extension_whitelist as $extension)
        {
        	if (strcasecmp($file_extension, $extension) == 0)
            {
            	$is_valid_extension = true;
                break;
            }
        }
        if (! $is_valid_extension)
        {
        	echo "Invalid file extension";
            exit(0);
        }
        
        //保存图片
        $filename = $_FILES[$upload_name]["tmp_name"];
        $targetname = $save_path . $file_name;
		!@move_uploaded_file($filename, $targetname);
        $output['fileName'] = $file_name;
		$this->output->set_content_type('application/json')->set_output(json_encode($output));
	}
}
